var async = require('async');
var moment = require('moment');
var superagent = require('superagent');
var CommonUtil = require('../../../../../common/util/CommonUtil');
var CONFIG = require('../../../../../common/config');
var CODE = require('../../../../../common/code');
var luaUtil = require('./luaUtil');

var YjxOrgRModel = require('../../../../../common/yjxMysql/mapping/YjxOrgRModel');
var YjxOrgModel = require('../../../../../common/yjxMysql/mapping/YjxOrgModel');
var YjxThirdPartyUserModel = require('../../../../../common/yjxMysql/mapping/YjxThirdPartyUserModel');
var YjxUserModel = require('../../../../../common/yjxMysql/mapping/YjxUserModel');
var YjxMemberModel = require('../../../../../common/yjxMysql/mapping/YjxMemberModel');


var usersUtil = (function () {

    function usersUtil() {
    }


    /**
     * 中台系统账号密码登录
     * @author xc
     * @date 2018-07-09
     *
     * @param account  用户名
     * @param password 密码(经过MD5加密)
     * @param orgTypes 所属组织类型(数组:[100,300,400])
     *
     * 参考: http://yapi.yijianxiu.com:7000/mock/34/yjx/v1/api4back/users/middleStageLogin
     */
    usersUtil.midStageLogin = function(param, callback) {
        var userEnt = new YjxUserModel;
        userEnt.getUserInfoByAcAndPw(param, function(findErr, findRet){
            if(findErr) {
                return callback('系统异常', null);
            }

            if(findRet && findRet.length>0) {
                var uInfo = findRet[0];

                // 用户信息
                var retInfo = {
                    userInfo: {
                        userId: uInfo.user_id,
                        nickName: uInfo.nickname||'',
                        avatarUrl: uInfo.profile_photo||''
                    },
                    orgInfo: []
                };
                // 组织信息
                for(var i=0;i<findRet.length;i++) {
                    var tmpInfo = findRet[i];
                    if(tmpInfo.user_id == uInfo.user_id) {
                        retInfo.orgInfo.push({
                            orgId: tmpInfo.org_id,
                            orgType: tmpInfo.org_type,
                            orgName: tmpInfo.org_name,
                            role: tmpInfo.role
                        });

                    } else {
                        // 取[匹配到的第一个]用户相关组织
                        break;
                    }
                }

                return callback(null, retInfo);

            } else {
                return callback('登陆失败', null);
            }
        });
    };



    return usersUtil;
})();

module.exports = usersUtil;